<?php
	class modelControl extends commonControl{
		/**
		 * 显示模型列表
		 */
		public function index() {
			$db = M("model");
			$row = $db->all();
			$this->assign("model", $row);
			$this->display();
		}
		/**
		 * 显示添加模型页面
		 */
		public function add_show(){
			$this->display();
		}
		/**
		 * 执行模型添加
		 */
		public function add_exe(){
			$_POST['ptable'] = $ptable = $_POST['mname']; //主表名
			$model = M();
			$sql = array();
			$charset = C('CHARSET'); //默认字符集
				if ($_POST['createtable'] == 1) {
					$sql['p'] = "create table if not exists " . $ptable .
					" (id int primary key auto_increment,title varchar(100) not null default '',
                        addtime int(10) not null default 0,status tinyint(1) not null default 1,click int not null default 0,keywords varchar(45) not null default '',description varchar(200) not null default '',uid int not null,catid smallint not null,	
                       recycled tinyint(1) not null default 0,allow_comment tinyint(1) not null default 1,gourl varchar(100) not null default '',thumb varchar(100) not null default '',
						updatetime int(10) not null default 0,comments smallint not null default 0) CHARSET " . $charset;
					$_POST['stable'] = $stable = $ptable . '_data'; //附表
					$sql['s'] = "create table if not exists " . $stable . "(
                                nid int unique not null,body text not null,template varchar(100) not null default '',source varchar(45) not null default '',userip char(15) not null default ''
                        )  CHARSET " . $charset;
				} else {
					$sql['p'] = "create table if not exists " . $ptable . "
                (id int primary key auto_increment,title varchar(100) not null default '',body text not null default '',
                addtime int(10) not null default 0,status tinyint(1) not null default 1,click int not null default 0,keywords varchar(45) not null default '',description varchar(200) not null default '',uid int not null,catid smallint not null,
                template varchar(100) not null default '',allow_comment tinyint(1) not null default 1,,comments smallint not null default 0
                ) CHARSET " . $charset;
					$_POST['stable'] = '';
				}
			foreach($sql as $v){
				if($model->query($v)){
					$this->error("创建副数据表失败!");
				}
			}
			if($model->table("model")->add()){
            	$this->success("添加模型成功", "index");
       		}else{
            	$this->error("添加模型失败", "index");
       		}
		}
		/**
		 * 字段显示
		 */
		public function field_show(){
			$mid = $_GET['mid'];
			$field = K('admin/model_fieldView');
			$prefix = C('DB_PREFIX'); //表前缀
			$row = $field->where($prefix."model_field.mid = '".$_GET['mid']."'")->all();
			$this->assign('field', $row);
			$this->display();
		}
		/**
		 * 增加字段显示
		 */
		public function field_add_show(){
			$mid = $_GET['mid'];
			$model = M('model'); //实例化模型 为求出$_GET['mid']模型的信息
			$model_row = $model->where(" mid = '".$mid."'")->find();
			$this->assign('model', $model_row);
			$this->display();
		}
		/**
		 * 执行增加字段
		 */
		public function field_add_exe(){
			$db = M("model_field");
			//组成新建字段的sql
			$db->validate = array(
					array('fname','nonull','字段名不能为空',2),
					array('fname','regexp:/^[a-z][a-z0-9]+$/i','字段请不要用用中文或者首位不要为数字',2),
			);
			if(!$db->validate()){
				$this->error($db->error);
			}
			$fieldsize = !empty($_POST['fieldset']['fieldsize'])?'('.$_POST['fieldset']['fieldsize'].') ' :''; //限定字段长度
			$defaultvalue = empty($_POST['fieldset']['value'])?'': " DEFAULT '".$_POST['fieldset']['value'] ."' "; //默认值 
			$fieldname = $_POST['fname']; //要 添加的字段名
			$fieldtype = $_POST['fieldset']['fieldtype']; //要添加的字段的类型
			$tablename = $_POST['tablename'];
			$sql = "ALTER TABLE " . $tablename . " ADD " . $fieldname . " " .$fieldtype .$fieldsize .' NOT NULL '.$defaultvalue;
			//P($sql);
			$db->exe($sql);
			$_POST['fieldset'] = var_export($_POST['fieldset'], true); //fieldset是用来设定在后台显示的样式
			//P($_POST);exit;
			if($db->add()){
				$this->write_catch_field($_POST['mid']); //生成字段缓存数据
				$this->success('创建字段成功','index');
			}else{
				$this->error('创建字段成功');
			}
		}
		/**
		 * 字段修改视图
		 */
		public function field_modify(){
			
			$fid = $_GET['fid'];
			$field = M('model_field');
			$old_f = $field->find($fid);
			$fieldset = array();
			eval('$fieldset = '.$old_f['fieldset'].';');
			$old_f['fieldset'] = $fieldset;
			
			$model = M('model'); //实例化模型 为求 该模型是否为单表还是两张表
			$model_row = $model->where(" mid = '".$old_f['mid']."'")->find();
			$this->assign('model', $model_row);
			$this->assign('fields', $old_f);
			P($old_f);
			$this->display();
		}
		/**
		 * 执行那个字段修改
		 */
		public function field_modify_exe(){
			$prefix = C('DB_PREFIX'); //表前缀
			$model_field = M('model_field');
			$model_field->validate = array(
						array('fname','nonull','字段名不能为空',2),
						array('fname','regexp:/^[a-z][a-z0-9]+$/i','字段请不要用用中文或者首位不要为数字',2),
					);
			if(!$model_field->validate()){
				$this->error($this->error);
			}else{ //通过验证
				$tablename = $_POST['tablename'];
				$oldfieldname = $_POST['old_field_name'];
				$dropfieldsql = 'alter table `'.$tablename.'` drop column ' . $oldfieldname;
				//P($droptablesql);exit;
				$model_field->exe($dropfieldsql); //删除要修改的表字段
				
				$model_field->del("fid = '".$_POST['old_field_fid']."'");   //删除要修改model_field中的那一行
				$addfieldsql  = "ALTER TABLE " . $tablename . " ADD " .
              	$_POST['fname'] . " " . $_POST['fieldset']['fieldtype'] . "(" . $_POST['fieldset']['fieldsize'] .
                ") NOT NULL DEFAULT '" . $_POST['fieldset']['value'] . "'";
				$model_field->exe($addfieldsql);//增加要修改的表
				$_POST['fieldset'] = var_export($_POST['fieldset'], true); //fieldset是用来设定在后台显示的样式
				if($model_field->add()){
					$this->write_catch_field($_POST['mid']); //生成字段缓存数据
					$this->success('修改字段成功','index');
				}else{
					$this->error('修改字段成功');
				}
			}
		}
		/**
		 * 执行字段删除
		 */
		public function field_del(){
			$dropfid = $_GET['fid'];
			$prefix = C('DB_PREFIX'); //表前缀
			$model_field = M('model_field');
			$dropfield = $model_field->find($dropfid);//获取要删除字段的信息
			$tablename = $dropfield['tablename']; //该字段所在的表
			$fieldname = $dropfield['fname']; //改字段名称
			$fid = $dropfield['fid']; //改字段的fid
			$mid = $dropfield['mid'];
			
			$dropfieldsql = 'alter table `'.$tablename.'` drop column ' . $fieldname; //删除 改字段所在的模型sql
			$model_field->exe($dropfieldsql); //执行删除字段操作
			$model_field->del(" fid = '".$fid."'"); //删除model_field中的改字段的一行数据
			$this->write_catch_field($mid); //重写字段缓存数据
			$this->success('恭喜修改成功');
		}
		/**
		 * 将字段写入缓存
		 */
		public function write_catch_field($mid) {
			$db = M("model_field");
			$fields = $db->all("mid='$mid'");
			$catchStr = '';
			$catchStr.="<?php if(!defined('PATH_HD'))exit;\n return ";
			$catchStr.=var_export($fields, true). ";\n ?>";
			$dir = dir::create('./data/field'); //建立缓存目录
			if(file_put_contents('./data/field/field_' . $mid . '.php', $catchStr)){
				return true;
			}else{
				return false;
			}
		}
		/**
		 * 模型修改显示页面
		 */
		public function model_modify_show(){
			$model = M('model');
			$this->assign('model', $model->find(" mid = '".$_GET['mid']."'"));
			$this->display();
		}
		/**
		 * 执行模型修改
		 */
		public function model_modify_exe(){
			$model = M('model');
			if($model->update()){
				$this->success('恭喜修改成功','index');
			}else{
				$this->error('可惜，修改失败了！');
			}
		}
		/**
		 * 模型删除
		 */
		public function model_del(){
			$prefix = C('DB_PREFIX'); //表前缀
			$mid = $_GET['mid'];
			$db = M("model");
			if ($db->table("category")->find("mid='$mid'")) {
				$this->error("请删除此模型下的栏目");
			}
			$model_del = $db->table('model')->find($mid);
			if($model_del['issystem'] == 1){
				$this->error('系统字段不允许删除');
			}
			$model = $db->find($mid);
			$sql = array();
			$sql['p'] = "drop table " .$prefix. $model['ptable'];
			if ($model['stable']) {
				$sql['s'] = "drop table " . $prefix .$model['stable'];
			}
			foreach ($sql as $s) {
            	$db->exe($s);
       		}
			$model_re = K('model_delRelation');
			$model = '';
			if($model_re->del(" mid = '".$_GET['mid']."'")){
				$this->success('恭喜删除成功!');
			}else{
				$this->error('可惜，删除失败了。');
			}
		}
		/**
		 * 重建模型缓存
		 */
		public function reset(){
			dir::del('./data/field');
			$model = M('model');
			$model_arr = $model->all();
			$models = arr2toArr1($model_arr, 'mid'); //获得所有的模型(一维数组)
			$field = M('model_field');
			$fields = $field->all();
			$error = 0 ; //定义错误基数
			foreach($models as $v){
				if(!$this->write_catch_field($v)){
					$error = 1;
				}
			}
			if($error ==1 ){
				$this->error('可惜，更新失败!');
			}else{
				$this->success('恭喜，更新成功');
			}
		}
	}

?>